#! -*- coding:utf-8 -*-
import logging
from pymongo import MongoClient
from common.utils.tz import local_now
from django.conf import settings
from common.utils import telegram
from common.settlement.model import Settlement
from django.core.management.base import BaseCommand

_LOGGER = logging.getLogger(__name__)

_TG_SETTLEMENT_GROUP = -290937016

mg = MongoClient(settings.MONGO_ADDR).paychannel_stat


def get_channel_today_income(channel_id):
    id = str(channel_id) + '_' + local_now().strftime('%Y%m%d')
    channel_daily_data = mg.channel_status.find_one({"_id": id})
    if channel_daily_data:
        return channel_daily_data['total']
    else:
        return 0


def get_channels_today_income(channel_id, chn_ids):
    if chn_ids == None:
        chn_ids = ''
    try:
        ids = [int(y) for y in chn_ids.split(',')]
    except Exception as e:
        ids = []
    if str(channel_id) not in chn_ids:
        ids.append(channel_id)
    income = 0
    for id in ids:
        income += get_channel_today_income(id)
    return income


class Command(BaseCommand):
    def handle(self, **options):
        items = Settlement.query.all()
        for item in items:
            channel_id = item.chn_id
            print channel_id
            income = get_channels_today_income(channel_id, item.chn_ids)
            increase = income - float(item.today_income)
            item.today_income = income
            if increase > 0:
                item.balance = float(item.balance) + increase
            item.save()

            if item.status == 1 and item.balance >= item.warning_amount:
                tg_msg = u'通道提现告警 结算ID: %s\n' % item.id
                tg_msg += item.name + '\n'
                tg_msg += u'当前余额: ' + str(item.balance) + '\n'
                telegram.send_text_msg_tele(_TG_SETTLEMENT_GROUP, tg_msg)
